package fr.lostnet;

import java.io.File;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.crypto.engines.DESedeEngine;
import org.bouncycastle.crypto.params.KeyParameter;
import org.tmatesoft.sqljet.core.SqlJetException;
import org.tmatesoft.sqljet.core.SqlJetTransactionMode;
import org.tmatesoft.sqljet.core.table.ISqlJetCursor;
import org.tmatesoft.sqljet.core.table.ISqlJetTable;
import org.tmatesoft.sqljet.core.table.SqlJetDb;

public class WgoDbEx {

	private static final String DES_SECRET = "cm3XRDWnfyCT78siqhqm9Tf0wZtybddE";
	private static final String TABLE_NAME = "radar";
	private static final String TABLE_FIELDS[] = { "LAT", "LONG", "DATA" };
	
	private static final String TEST_DATA[] = {
		"1FnuFErjJAxZraEawGx+H9g5v+ZJNDQnHEnMKJ9aLcRktE1X6OBSa2KbZwGn80Nl8064Do3r5cEAAAAAAAAAAAAAAAAAAAAA",
		"PVArqBj572G4Wj8ATngfP/1b+48mg2OxmVSGJkh2++g9Ca91HKOY/QsNfy5QBehouE2CrCKZtb0AAAAAAAAAAAAAAAAAAAAA",
		"P+zhntZcJGcD4nxhZS0y1NaJfxSEBD4T0y2df2et3U539vstGN+QiWDM/UjSFnWcufh7fp3P/kQAAAAAAAAAAAAAAAAAAAAA",
		"TnFH91qULCsJ5hsuVziaGRNaG0RN0QW1WOFzOOXnXIKEi5zJUAbiAMlFfWfePsSsjXMq5IdLf54AAAAAAAAAAAAAAAAAAAAA"
	};
	
	public static void main(String[] args) throws Exception {
		if (args.length == 0) {
			for (int i = 0; i < TEST_DATA.length; i ++) {
				System.out.println("Testing decryption :" + wgoDecrypt(TEST_DATA[i]));
			}
		}
		else {
			System.out.println("Reading database :" + args[0]);
			wgoDatabase(args[0]);
		}
	}

	private static String wgoDecrypt(String encrypted) {
		DESedeEngine engine = new DESedeEngine();
		byte encryptedBytes[] = Base64.decodeBase64(encrypted);
		byte secretBytes[] = Base64.decodeBase64(DES_SECRET);
		byte plainBytes[] = new byte[encryptedBytes.length];
		engine.init(false, new KeyParameter(secretBytes));
		for (int i = 0; i < encryptedBytes.length; i += 8) {
			engine.processBlock(encryptedBytes, i, plainBytes, i);
		}
		return new String(plainBytes);
	}

	private static void wgoDatabase(String dbName) throws SqlJetException {
		SqlJetDb db = SqlJetDb.open(new File(dbName), false);
		db.beginTransaction(SqlJetTransactionMode.READ_ONLY);
		ISqlJetTable table = db.getTable(TABLE_NAME);
		ISqlJetCursor cursor = table.order(table.getPrimaryKeyIndexName());
		if (!cursor.eof()) {
			do {
				System.out.println(cursor.getRowId() + ";"
						+ cursor.getFloat(TABLE_FIELDS[0]) + ";"
						+ cursor.getFloat(TABLE_FIELDS[1]) + ";"
						+ wgoDecrypt(cursor.getString(TABLE_FIELDS[2])));
			} while (cursor.next());
		}
		cursor.close();
		db.close();
	}
	
}
